﻿using System;
namespace ORS.OrderRobot
{
    /// <summary>
    /// 重试帮助类
    /// </summary>
    public static class RetryHelper
    {
        public static async Task<T> RetryWithFixAsync<T>(
            Func<Task<T>> operation,
            Func<CodeException, Task<(bool shouldRetry, int maxRetry)>> handleFixWithRetryCount,
            Func<int, Exception?, Task>? onRetry = null,
            int delayMilliseconds = 10)
        {
            var retryCounts = new Dictionary<Type, int>();
            int totalRetryCount = 0;
            while (true)
            {
                try
                {
                    return await operation();
                }
                catch (CodeException ex)
                {
                    totalRetryCount++;
                    var exType = ex.GetType();
                    var (shouldRetry, maxRetry) = await handleFixWithRetryCount(ex);
                    if (!shouldRetry)
                    {
                        throw;
                    }
                    retryCounts.TryGetValue(exType, out int currentRetryCount);
                    if (currentRetryCount >= maxRetry)
                    {
                        throw;
                    }
                    retryCounts[exType] = currentRetryCount + 1;
                    await onRetry?.Invoke(totalRetryCount, ex);
                    await Task.Delay(delayMilliseconds);
                }
            }
        }
    }
}

